package com.rpc.example.codec;

import com.rpc.example.core.Header;
import com.rpc.example.core.Protocol;
import com.rpc.example.serial.ISerial;
import com.rpc.example.serial.SerializeManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Elvis
 * @version 1.0, 2022/11/10
 */
@Slf4j
public class RpcEncode extends MessageToByteEncoder<Protocol<Object>> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Protocol<Object> o, ByteBuf byteBuf) throws Exception {
        Header header = o.getHeader();
        log.info("+++++++++start encode {}++++++++++++", header.getRequestType());
        Object content = o.getData();
        byteBuf.writeShort(header.getMagic());
        byteBuf.writeByte(header.getSerializeType());
        byteBuf.writeByte(header.getRequestType());
        byteBuf.writeLong(header.getRequestId());

        ISerial iSerial = SerializeManager.getSerializer(header.getSerializeType());
        byte[] bytes = iSerial.serialized(content);
        byteBuf.writeInt(bytes.length);
        header.setDataLength(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
